import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: { title: '首页' }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { title: '登录', guest: true }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue'),
      meta: { title: '注册', guest: true }
    },
    {
      path: '/documents',
      name: 'documents',
      component: () => import('../views/DocumentListView.vue'),
      meta: { title: '我的文档', requiresAuth: true }
    },
    {
      path: '/documents/create',
      name: 'document-create',
      component: () => import('../views/DocumentCreateView.vue'),
      meta: { title: '创建文档', requiresAuth: true }
    },
    {
      path: '/documents/:id',
      name: 'document-edit',
      component: () => import('../views/DocumentEditView.vue'),
      meta: { title: '编辑文档', requiresAuth: true }
    },
    {
      path: '/templates',
      name: 'templates',
      component: () => import('../views/TemplateListView.vue'),
      meta: { title: '文档模板' }
    },
    {
      path: '/templates/create',
      name: 'template-create',
      component: () => import('../views/TemplateCreateView.vue'),
      meta: { title: '创建模板', requiresAuth: true, requiresAdmin: true }
    },
    {
      path: '/templates/:id',
      name: 'template-detail',
      component: () => import('../views/TemplateDetailView.vue'),
      meta: { title: '模板详情' }
    },
    {      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue'),
      meta: { title: '关于' }
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('../views/UserProfileView.vue'),
      meta: { title: '个人中心', requiresAuth: true }
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      component: () => import('../views/NotFoundView.vue'),
      meta: { title: '页面未找到' }
    }
  ],
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = `${to.meta.title || '在线文档'} - 在线协作文档平台`
  
  const userStore = useUserStore()
  
  // 如果用户未登录但有token，尝试获取用户信息
  if (!userStore.isLoggedIn && localStorage.getItem('token')) {
    try {
      await userStore.initUser()
    } catch (error) {
      console.error('Failed to initialize user:', error)
    }
  }
  
  // 检查是否需要登录权限
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next({ name: 'login', query: { redirect: to.fullPath } })
    return
  }
  
  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin && !userStore.isAdmin) {
    next({ name: 'home' })
    return
  }
  
  // 已登录用户不能访问游客页面
  if (to.meta.guest && userStore.isLoggedIn) {
    next({ name: 'home' })
    return
  }
  
  next()
})

export default router
